import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import SearchArea from 'components/search-area'
import { Button } from 'antd'
import menuRoute from 'routes/menuRoute'
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
import NewCreditModel from 'containers/credit-setting/credit-model/new-credit-model'
import SlideFrame from 'components/slide-frame'
import baseService from 'share/base.service'
import errorMessage from 'share/errorMessage'
import ResizeTable from 'components/resize-table';

class CreditModel extends React.Component{
  constructor(props) {
    super(props);
    const { company } = this.props;
    this.defaultSetOfBooks = {
      label: company.setOfBooksName,
      key: company.setOfBooksId
    };
    this.state = {
      showSlideFrame: false,
      searchForm: [{
        type: 'selector',
        id: 'setOfBooksId',
        label: messages('credit-setting.key86')/*帐套*/,
        labelKey: 'setOfBooksName',
        valueKey: 'id',
        selectorType: 'setOfBooksByTenant',
        defaultValue: this.defaultSetOfBooks
      },{
        type: 'input', id: 'modelName', label: messages('credit-setting.key87')/*信用模型名称*/
      },{
        type: 'input', id: 'modelCode', label: messages('credit-setting.key88')/*信用模型代码*/
      }],
      columns: [{
        title: messages('credit-setting.key88')/*信用模型代码*/, dataIndex: 'modelCode'
      },{
        title: messages('credit-setting.key87')/*信用模型名称*/, dataIndex: 'modelName'
      },{
        title: messages('credit-setting.key89')/*所属帐套*/, dataIndex: 'setOfBooksId', render: this.getSetOfBooksName
      },{
        title: messages('credit-setting.key3')/*信用类型*/, dataIndex: 'modelTypeId', render: modelTypeId => messages('credit-setting.key13')/*报销信用*/
      },{
        title: messages('credit-setting.key90')/*生效时间*/, dataIndex: 'startDate', render: startDate => new Date(startDate).format('yyyy-MM-dd')
      },{
        title: messages('credit-setting.key91')/*失效时间*/, dataIndex: 'endDate', render: endDate => endDate ? new Date(endDate).format('yyyy-MM-dd') : '-'
      },{
        title: messages('common.operation')/*操作*/, dataIndex: 'operate', render: (text,record) => (
          <span>
            <a onClick={e => this.handleEdit(record)}>{messages('common.edit')/*编辑*/}</a>
            <span className="ant-divider"/>
            <a onClick={() => this.context.router.push(menuRoute.getRouteItem('credit-model-detail').url.replace(':id', record.id))}>{messages('credit-setting.key92')/*详情设置*/}</a>
          </span>
        )
      }],
      pagination: {
        total: 0
      },
      searchParams: {
        setOfBooksId: this.defaultSetOfBooks.key
      },
      page: 0,
      size: 10,
      data: [],
      nowData: {},
      setOfBooks: [],
      loading: false
    }
  }

  getSetOfBooksName = id => {
    let target = this.state.setOfBooks.find(c => c.id === id);
    return target ? target.setOfBooksName : '-'
  };

  componentWillMount(){
    this.getList();
    this.getSetOfBooks();
  }

  getSetOfBooks = () => {
    baseService.getSetOfBooksByTenant().then(res => {
      this.setState({ setOfBooks: res.data })
    })
  };

  getList = () => {
    const { page, size, searchParams } = this.state;
    this.setState({ loading: true });
    creditModelService.getCreditModelList(Object.assign({}, searchParams, { page, size })).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false });
    })
  };

  search = result => {
    this.setState({ page: 0, searchParams: result }, this.getList);
  };

  clear = () => {
    this.setState({ page: 0, searchParams: {
      setOfBooksId: this.defaultSetOfBooks.key
    } }, this.getList);
  };

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({page: page - 1}, this.getList)
  };

  handleNew = () => {
    this.setState({
      showSlideFrame: true,
      nowData: {}
    })
  };

  handleEdit = record => {
    let setOfBooksName = this.getSetOfBooksName(record.setOfBooksId);
    let nowData = JSON.parse(JSON.stringify(record));
    nowData.setOfBooksId = {
      key: nowData.setOfBooksId,
      label: setOfBooksName
    };
    this.setState({
      showSlideFrame: true,
      nowData
    })
  };

  handleCloseFrame = flag => {
    this.setState({ showSlideFrame: false });
    if(flag){
      this.getList()
    }
  };

  render() {
    const { searchForm, pagination, columns, data, showSlideFrame, nowData, loading } = this.state;
    return (
      <div>
        <SearchArea searchForm={searchForm}
                    submitHandle={this.search}
                    clearHandle={this.clear}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          size="middle"
          bordered
          rowKey="id"
          pagination={pagination}
          dataSource={data}
          loading={loading}/>
        <SlideFrame show={showSlideFrame}
                    params={{
                      showSlideFrame,
                      nowData
                    }}
                    title={nowData.id ? messages('credit-setting.key93')/*编辑模型*/ : messages('credit-setting.key94')/*新建模型*/}
                    onClose={() => this.setState({ showSlideFrame: false })}
                    content={NewCreditModel}
                    afterClose={this.handleCloseFrame}/>
      </div>
    )
  }
}

CreditModel.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}

export default connect(mapStateToProps)(CreditModel)
